import { Button, Form, Input, Select, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { apiUserSetting, changeUserSetting, changePassword, apiCollege } from '@/api/api'
import './index.css'
const { Option } = Select;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 10, span: 20 },
};

const MySetting = () => {
  const [errorMsg, setErrorMsg] = useState('')
  const [userSetting, setUserSetting] = useState({})
  const [college, setCollege] = useState([])



  useEffect(() => {
    apiCollege().then((res) => {
      setCollege(res.data)
    })
    apiUserSetting().then((res) => {
      setUserSetting(res.data)
    })

  }, []);
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  form1.setFieldValue({ userName: "111" })
  // 重置个人信息表单
  const onResetInformation = () => {
    form1.resetFields();
  };
  // 提交个人信息表单
  // console.log(form1.getFieldValue(`major`));
  const onFinishInformation = (values) => {
    // values是个人信息表中所有Form.Item的值
    const information = {
      collegeId: userSetting.collegeId,
      collegeName: values.college,
      level: values.grade,
      major: values.major,
      nickName: values.userName,
      photoUrl: values.picUrl,
      userId: userSetting.userId,
      userName: userSetting.userName
    }

    changeUserSetting(information).then(
      (res) => {
        console.log(res);
        message.success('修改个人信息成功')
      }
    ).catch()

  };
  // 重置修改密码表单
  const onResetPassword = () => {
    form2.resetFields();
  };
  // 提交修改密码表单
  const onFinishPassword = () => {
    const confirmPassword = form2.getFieldValue('nowPassword').toString()
    const newpassword = form2.getFieldValue('newPassword').toString()
    const information = {
      password: confirmPassword,
      newPassword: newpassword
    }

    changePassword(information).then(
      (res) => {
        console.log(res);
        if (res.code===200) { 
          message.success('修改密码成功') 
        }
      }
    ).catch((error => {
      message.error(error.message)
    }))

  };
  const confirmNowPassword = (_, value) => {
    const pattern = /^(?=.*[0-9A-Za-z@%_])[0-9A-Za-z@%_]{8,}$/;
    const validPattern = value && pattern.test(value);
    if (!value) {
      return Promise.reject(new Error('输入为空'))
    }
    else if (!validPattern) {
      return Promise.reject(new Error('输入不符合规范'))
    }
    return validPattern ? Promise.resolve() : Promise.reject(new Error('输入不合法'));
  }
  const confirmNewPassword = (_, value) => {

    // 定义正则
    const pattern = /^(?=.*[0-9A-Za-z@%_])[0-9A-Za-z@%_]{8,}$/;
    // 校验长度
    const validLength = value && value.length > 8
    // 校验正则
    const validPattern = value && pattern.test(value);
    // 校验新旧密码是否相等
    if (!value) {
      return Promise.reject(new Error('输入为空'))
    }
    else if (errorMsg === "新密码必须满足：至少包含字符、数字和字母的其中两种") {
      return Promise.reject(new Error('新密码不能和前三次密码相同'))
    } else if (!validLength) {
      return Promise.reject(new Error('输入长度不合法'))
    }
    return validPattern ? Promise.resolve() : Promise.reject(new Error('输入不合法'));
  }
  const confirmPassword = (_, value) => {
    // 获取新旧密码的值
    const newpassword = form2.getFieldValue('newPassword')
    const confirmPassword = form2.getFieldValue('confirmPassword')
    // 定义正则
    const pattern = /^(?=.*[0-9A-Za-z@%_])[0-9A-Za-z@%_]{8,}$/;
    // 校验长度
    const validLength = value && value.length > 6 && value.length < 16;
    // 校验正则
    const validPattern = value && pattern.test(value);
    // 校验新旧密码是否相等
    const validMatch = newpassword && confirmPassword && newpassword == confirmPassword;
    if (!value) {
      return Promise.reject(new Error('输入为空'))
    }
    else if (!validLength) {
      return Promise.reject(new Error('输入长度不合法'))
    } else if (!validMatch) {
      return Promise.reject(new Error('两次输入的密码不相同'))
    }
    return validLength && validPattern ? Promise.resolve() : Promise.reject(new Error('输入不合法'));
  }
  // 获取学校;
  const formColleage = college.map(item => ({
    value: item.collegeName,
    label: item.collegeName
  }))
  // console.log(userSetting.nickName);
  return (
    <>
      <div className='form-container'>
        <div className='form-wrapper'>
          {/* 修改个人信息表单 */}
          <div className='information-form'>
            <h3>修改信息</h3>
            <Form

              colon={false}
              {...layout}
              form={form1}
              name="change information"
              style={{ maxWidth: 600 }}
              onFinish={onFinishInformation}
            >
              {/* 用户名称 */}
              <Form.Item name="userName" label="用户名称：" rules={[{ required: true, message: '请输入用户名' }]}  >
                <Input style={{ width: '300px' }} placeholder={userSetting.nickName} />
              </Form.Item>
              {/* 头像地址 */}
              <Form.Item name="picUrl" label="头像地址：" rules={[{ required: true, message: '请输入头像地址' }]}>
                <Input style={{ width: '300px' }} placeholder={userSetting.photoUrl} />
              </Form.Item>
              {/* 学校 */}
              <Form.Item name='college' label="学校" rules={[{ required: true }]}>
                <Select
                  showSearch
                  style={{ width: 200 }}
                  placeholder={userSetting.collegeName}
                  optionFilterProp="children"
                  filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  filterSort={(optionA, optionB) =>
                    (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                  }
                  options={formColleage}
                />
              </Form.Item>

              {/* 学院 */}
              <Form.Item name='major' label="学院" rules={[{ required: true }]}>
                <Select
                  showSearch
                  style={{ width: 200 }}
                  placeholder={userSetting.major}
                  optionFilterProp="children"
                  filterOption={(input, option) => (option?.label ?? '').includes(input)}
                  filterSort={(optionA, optionB) =>
                    (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                  }
                  options={[
                    {
                      value: '计算机科学与技术学院',
                      label: '计算机科学与技术学院',
                    },
                    {
                      value: '材料与冶金学院',
                      label: '材料与冶金学院',
                    },
                    {
                      value: '城市建设学院',
                      label: '城市建设学院',
                    },
                    {
                      value: '管理学院（恒大管理学院）',
                      label: '管理学院（恒大管理学院）',
                    },
                    {
                      value: '国际学院',
                      label: '国际学院',
                    },
                    {
                      value: '化学与化工学院',
                      label: '化学与化工学院',
                    },
                    {
                      value: '机械自动化学院',
                      label: '机械自动化学院',
                    },
                    {
                      value: '理学院',
                      label: '理学院',
                    },
                    {
                      value: '马克思主义学院',
                      label: '马克思主义学院',
                    }
                  ]}
                />
              </Form.Item>

              {/* 级别 */}
              <Form.Item name="grade" label="级别:" rules={[{ required: true, message: '请选择你的年级' }]}>
                <Select
                  placeholder="2023"
                  allowClear
                  style={{ width: '300px' }}
                >
                  <Option value="2023">2023</Option>
                  <Option value="2022">2022</Option>
                  <Option value="2021">2021</Option>
                </Select>
              </Form.Item>
              {/* 下方按钮 */}
              <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit">
                  确认修改
                </Button>
                <Button htmlType="button" onClick={onResetInformation}>
                  重置
                </Button>
              </Form.Item>

            </Form>
          </div>
          {/* 分割线 */}
          <div className='form-divider' />
          {/* 修改密码表单 */}
          <div className='password-form'>
            <h3>修改密码</h3>
            <Form
              {...layout}
              form={form2}
              name="change password"
              style={{ maxWidth: 600 }}
              onFinish={onFinishPassword}
            >

              {/* 当前密码 */}
              <Form.Item
                name="nowPassword"
                label="当前密码："
                rules={[
                  {
                    validator: (_, value) => {
                      return confirmNowPassword(_, value)
                    }

                  },
                ]}

              >
                <Input.Password style={{ width: '300px' }} />
              </Form.Item>
              {/* 新密码 */}
              <Form.Item name="newPassword" label="新密码：" rules={[
                {
                  validator: (_, value) => {
                    return confirmNewPassword(_, value)
                  }
                }
              ]}>
                <Input.Password style={{ width: '300px' }} />
              </Form.Item>
              {/* 确认新密码 */}
              <Form.Item name="confirmPassword" label="确认新密码：" rules={[{
                validator: (_, value) => {
                  return confirmPassword(_, value)
                }
              }]}>
                <Input.Password style={{ width: '300px' }} />
              </Form.Item>
              {/* 下方按钮 */}
              <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit">
                  确认修改
                </Button>
                <Button htmlType="button" onClick={onResetPassword}>
                  重置
                </Button>
              </Form.Item>

            </Form>
          </div>
        </div>
      </div>
    </>

  );
};
export default MySetting;